from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import Qt
import pyqrcode
import io


class QRCodeGenerator:
    @staticmethod
    def generate_qrcode(url, size=300, error_correction='L'):
        """
        生成二维码并返回QPixmap

        参数:
            url: 要编码的URL或文本
            size: 二维码图片大小(像素)
            error_correction: 纠错级别(L/M/Q/H)
        """
        try:
            # 创建二维码
            qr = pyqrcode.create(url, error=error_correction)

            # 将二维码保存到内存中的字节流
            buffer = io.BytesIO()
            qr.png(buffer, scale=6, quiet_zone=2)  # scale控制大小，quiet_zone控制边距

            # 转换为QPixmap
            qimage = QImage()
            qimage.loadFromData(buffer.getvalue())
            pixmap = QPixmap.fromImage(qimage)

            return pixmap.scaled(size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation)

        except Exception as e:
            print(f"生成二维码失败: {str(e)}")
            # 返回错误占位图
            error_pixmap = QPixmap(size, size)
            error_pixmap.fill(Qt.white)
            return error_pixmap
